package controller.listeners;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import controller.decoders.EventDecoder;
import controller.decoders.KeyEventDecoder;
import controller.dispatchers.AbstractDispatcher;
import controller.factories.CommandFactory;

public class KeyboardListener implements KeyListener
{
	private KeyEvent event;
	private String eventString;
	private EventDecoder eventDecoder;
	private Thread worker;
	
	public KeyboardListener(
			AbstractDispatcher modelDispatcher,
			AbstractDispatcher viewDispatcher,
			CommandFactory modelCommandFactory,
			CommandFactory viewCommandFactory)
	{
		this.eventDecoder = new KeyEventDecoder(
				this, 
				modelDispatcher,
				viewDispatcher, 
				modelCommandFactory, 
				viewCommandFactory);
		
		startWorker();
		
		System.out.println("[CONTROLLER] " + toString() + " created a " + 
				eventDecoder.toString() + " worker thread.");
	}
	
	public void startWorker()
	{
		// Start a worker thread
		this.worker = new Thread(this.eventDecoder);
		this.worker.start();
	}
	
	// terminate the worker thread
	public void killTheMotherfucker()
	{
		worker.interrupt();
		System.out.println("[CONTROLLER] Worker thread terminated! ");
	}

	public void keyPressed(KeyEvent e)
	{
		synchronized (eventDecoder)
		{
			this.event = e;
			this.eventString = "p " + e.getKeyChar();
			eventDecoder.notify();
		}
	}

	public void keyReleased(KeyEvent e)
	{
		synchronized (eventDecoder)
		{
			this.event = e;
			this.eventString = "r " + e.getKeyChar();
			eventDecoder.notify();
		}
	}
	
	public void keyTyped(KeyEvent e)
	{
		synchronized (eventDecoder)
		{
			this.event = e;
			eventDecoder.notify();
		}
	}

	public KeyEvent getKeyEvent()
	{
		return event;
	}
	
	public String getEventString()
	{
		return eventString;
	}
	
	public EventDecoder getEventDecoder()
	{
		return eventDecoder;
	}
	
	public String toString()
	{
		return this.getClass().getSimpleName();
	}
}
